import {commonUrl, managerUrl, getRequest, getRequestWithNoToken, postRequestWithNoToken,uploadFileRequest,uploadFile} from '@/libs/axios';
import { getCookie } from "@/libs/storage.js";
import axios from "axios";

// 通过id获取子地区
export const getChildRegion = (id) => {
  return getRequest(`${commonUrl}/common/common/region/item/${id}`);
};

// 点地图获取地址信息
export const getRegion = (params) => {
  return getRequest(`${commonUrl}/common/common/region/region`, params);
};

// 获取拼图验证
export const getVerifyImg = (verificationEnums) => {
  return getRequestWithNoToken(`${commonUrl}/common/common/slider/${verificationEnums}`);
};

// 拼图验证
export const postVerifyImg = (params) => {
  return postRequestWithNoToken(`${commonUrl}/common/common/slider/${params.verificationEnums}`, params);
};


// 获取系统基础信息
export const getBaseSite = () => {
  return getRequest(`${commonUrl}/common/common/site`);
};

// 上传文件
export const upLoadFile = (bold) =>{
  return uploadFileRequest(uploadFile,bold);
}

// 视频播放地址
export const videoUrl = (url, type = '.mp4', isPrivate = false) => {
  let priva = isPrivate ? 'private-o2o' : 'o2o';
  let accessToken = getCookie("accessToken");
  return `${commonUrl}/common/common/source/video/play?bucketName=${priva}&objectName=${url}${type}&accessToken=${accessToken}`
}

//导出
export const postExport = (url, data) => {
  let accessToken = getCookie("accessToken");
  return axios({
    method: `post`,
    url: `${managerUrl}/manager${url}`,
    data: data,
    headers: {
      accessToken: accessToken,
      "Content-Type": "application/json"
    },
    responseType: `blob`,
  });
};

// 根据视频生成封面图
export function uploadCover (file, fileName = 'cover.png') {
  return new Promise((resolve) => {
    const blob = new Blob([file]) // 文件转化成二进制文件
    const url = URL.createObjectURL(blob) // 转化成url
    // 视频
    const oVideo = document.createElement('video')
    oVideo.src = url
    oVideo.controls = 'controls'
    oVideo.currentTime = 1 // 设置当前视频为 第1s
    oVideo.addEventListener('canplay', () => {
      // 转base64
      const oCanvas = document.createElement('canvas')
      oCanvas.width = oVideo.videoWidth
      oCanvas.height = oVideo.videoHeight
      oCanvas.getContext('2d').drawImage(oVideo, 0, 0, oCanvas.width, oCanvas.height)
      const base64 = oCanvas.toDataURL('image/png')
      // 转图片
      const arr = base64.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      const file = new File([u8arr], fileName, { type: mime })
      if (file.size > 20908) { // 兼容火狐浏览器
        resolve(file)
      }
    })
  })
}
